/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * gestionarEntrega.java
 *
 * Created on 01-may-2011, 11:00:33
 *
 */

package interfaces.farmacia;
import Controlador.Controlador;
import GestorCitas.LineaReceta;
import GestorFarmacia.Entrega;
import GestorUsuarios.Usuario;
import clinica.ClinicaView;
import clinica.Interfaces;
import clinica.Interfaz;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.application.Action;
import javax.swing.ListSelectionModel;

/**
 *
 * @author Ana Ferreira Blanco
 */
public class gestionarEntrega extends javax.swing.JPanel {

    private ClinicaView app;
    private Interfaces _anterior;
    private Usuario _paciente;
    Entrega[] _entregas = null;



    /** Creates new form gestionarEntrega */
    public gestionarEntrega(ClinicaView a) {
        app = a;
        initComponents();
    }

    private void limpiarTabla() {
        while(((DefaultTableModel)panel_entregas_paciente.getModel()).getRowCount()>0)
            ((DefaultTableModel)panel_entregas_paciente.getModel()).removeRow(0);

    }

    public void rellenaDatos(Usuario u, Interfaces ant) throws SQLException, IOException, ClassNotFoundException, ParseException {
        
        limpiarTabla();
        _anterior = ant;
        _paciente = u;
        //Obtengo las recetas del paciente
        _entregas = Controlador.obtenerEntregas(u.getIdUsuario());
        LineaReceta linea = null;
        DateFormat fecha = new  SimpleDateFormat("dd/MM/yyyy");
        panel_entregas_paciente.setRowHeight(32);
        panel_entregas_paciente.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        //Para cada entrega, su línea de receta
        if (_entregas == null) { // No hay entregas => no se rellena la tabla
            app.abrirMensajeError("El paciente "+u.getNombre()+" "+u.getApellidos()+" no tiene ninguna entrega pendiente.", Interfaces.PRINCIPAL_FARMACEUTICO);
            return;
        }
        for(Entrega e:_entregas) {
            linea= e.getLineaReceta();
            //Valores a mostrar en la tabla
            String [] valores = {""+linea.getMedicamento().getNombreMedicamento(),""+linea.getNumTomas(),""+fecha.format(e.getFechaEntrega())};
            ((DefaultTableModel)panel_entregas_paciente.getModel()).addRow(valores);
        }
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        panel_entregas_paciente = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Entregas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, Interfaz.setFontSize()));
        jPanel1.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
        jPanel1.setMinimumSize(new java.awt.Dimension(780, 470));
        jPanel1.setName("jPanel1"); // NOI18N
        jPanel1.setPreferredSize(new java.awt.Dimension(452, 402));

        jScrollPane1.setFont(new java.awt.Font("Tahoma", 0, 18));
        jScrollPane1.setName("jScrollPane1"); // NOI18N

        panel_entregas_paciente.setFont(new java.awt.Font("Tahoma", 0, 18));
        panel_entregas_paciente.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Medicamento", "Cantidad", "Fecha de entrega"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        panel_entregas_paciente.setName("panel_entregas_paciente"); // NOI18N
        panel_entregas_paciente.setUpdateSelectionOnSort(false);
        jScrollPane1.setViewportView(panel_entregas_paciente);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 728, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 319, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(gestionarEntrega.class, this);
        jButton3.setAction(actionMap.get("cancelar")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(gestionarEntrega.class);
        jButton3.setIcon(resourceMap.getIcon("jButton3.icon")); // NOI18N
        jButton3.setLabel(resourceMap.getString("jButton3.label")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N

        jButton8.setAction(actionMap.get("entregar")); // NOI18N
        jButton8.setFont(Interfaz.setFontSize());
        jButton8.setIcon(resourceMap.getIcon("jButton8.icon")); // NOI18N
        jButton8.setText("Entregar");
        jButton8.setLabel(resourceMap.getString("jButton8.label")); // NOI18N
        jButton8.setName("jButton8"); // NOI18N
        jButton8.setPreferredSize(new java.awt.Dimension(0, 0));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 760, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 464, Short.MAX_VALUE)
                        .addComponent(jButton3)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 357, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3))
                .addContainerGap())
        );

        jButton3.getAccessibleContext().setAccessibleName("atras");
    }// </editor-fold>//GEN-END:initComponents

    /*@brief Evento del botón cancelar
     *Debe volver a la pantalla anterior
     */
    @Action
    public void cancelar() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, SQLException {
        app.volver(_anterior);
    }
    /*@brief Evento del botón aceptar
     *Muestra la pantalla siguiente con los datos de la entrega seleccionada
     */
    @Action
    public void entregar() throws SQLException, IOException, ClassNotFoundException, ParseException, NoSuchAlgorithmException {
        
        int row = panel_entregas_paciente.getSelectedRow();
        if ( row < 0 ) 
            app.abrirMensajeError("No se seleccionó ninguna entrega.", Interfaces.GESTIONAR_ENTREGA);
        else{
        Entrega e = _entregas[panel_entregas_paciente.getSelectedRow()];
        Usuario u = _paciente;

        app.abrirGestionarEntrega2(e,u,Interfaces.PRINCIPAL_FARMACEUTICO);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable panel_entregas_paciente;
    // End of variables declaration//GEN-END:variables

}
